import AMapNaviKit
import CryptoKit
import Foundation
import CommonCrypto
import AVFoundation

extension UIView {
    public func toImage() -> UIImage? {
        // 开始图形上下文
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0.0)
        defer { UIGraphicsEndImageContext() } // 确保上下文能被释放
        
        // 将view的layer渲染到图形上下文中
        layer.render(in: UIGraphicsGetCurrentContext()!)
        
        // 从图形上下文获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        return image
    }
}

extension String {
    public var powmd5: String {
        if #available(iOS 13, *) {
            let digest = Insecure.MD5.hash(data: self.data(using: .utf8) ?? Data())
            return digest.map { String(format: "%02hhx", $0) }.joined()
        } else {
            let data = Data(self.utf8)
            var hash = [UInt8](repeating: 0,  count: Int(CC_MD5_DIGEST_LENGTH))
            data.withUnsafeBytes {
                _ = CC_MD5($0.baseAddress, CC_LONG(data.count), &hash)
            }
            return hash.map { String(format: "%02x", $0) }.joined()
        }
    }
}

public func polylineWithLnglatStringArray(lnglatString:[String]) -> MAPolyline? {
    var coordinates = [CLLocationCoordinate2D]()
    for lnglat in lnglatString {
        let lnglatArr = lnglat.components(separatedBy: ",")
        if lnglatArr.count == 2 {
            let lng = Double(lnglatArr[0].trimmingCharacters(in: .whitespacesAndNewlines))!
            let lat = Double(lnglatArr[1].trimmingCharacters(in: .whitespacesAndNewlines))!
            let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng)
            coordinates.append(coordinate)
        }
    }
    let polyline = MAPolyline(coordinates: &coordinates, count: UInt(coordinates.count))
    return polyline
    
}

public func polygonWithLnglatStringArray(lnglatString:[String]) -> MAPolygon? {
    var coordinates = [CLLocationCoordinate2D]()
    for lnglat in lnglatString {
        let lnglatArr = lnglat.components(separatedBy: ",")
        if lnglatArr.count == 2 {
            let lng = Double(lnglatArr[0].trimmingCharacters(in: .whitespacesAndNewlines))!
            let lat = Double(lnglatArr[1].trimmingCharacters(in: .whitespacesAndNewlines))!
            let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng)
            coordinates.append(coordinate)
        }
    }
    let polygon = MAPolygon(coordinates: &coordinates, count: UInt(coordinates.count))
    return polygon
}

public func addMoveAnimationWith(lnglatString:[String], animateAnnotation:MAAnimatedAnnotation, duration: Double, finishCallback: @escaping (Bool) -> Void) {
    var coordinates = [CLLocationCoordinate2D]()
    for lnglat in lnglatString {
        let lnglatArr = lnglat.components(separatedBy: ",")
        if lnglatArr.count == 2 {
            let lng = Double(lnglatArr[0].trimmingCharacters(in: .whitespacesAndNewlines))!
            let lat = Double(lnglatArr[1].trimmingCharacters(in: .whitespacesAndNewlines))!
            let coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng)
            coordinates.append(coordinate)
        }
    }
    animateAnnotation.addMoveAnimation(withKeyCoordinates: &coordinates, count: UInt(coordinates.count), withDuration: duration, withName: nil) { finish in
        print("动画结束")
        finishCallback(finish)
    }
}

public class PowSpeechSynthesizer: NSObject, AVSpeechSynthesizerDelegate {
    public static let Shared = PowSpeechSynthesizer()
    
    private var speechSynthesizer: AVSpeechSynthesizer!
    
    private override init(){
        super.init()
        
        buildSpeechSynthesizer()
    }
    
    public func speak(_ aString: String) {
        
        let aUtterance = AVSpeechUtterance(string: aString)
        aUtterance.voice = AVSpeechSynthesisVoice(language: "zh-CN")
        
        //iOS语音合成在iOS8及以下版本系统上语速异常
        let sysVer = (UIDevice.current.systemVersion as NSString).doubleValue
        if sysVer < 8.0 {
            aUtterance.rate = 0.25//iOS7设置为0.25
        }
        else if sysVer < 9.0 {
            aUtterance.rate = 0.15//iOS8设置为0.15
        }
        
        if speechSynthesizer.isSpeaking {
            speechSynthesizer.stopSpeaking(at: .word)
        }
        
        speechSynthesizer.speak(aUtterance)
    }
    
    public func isSpeaking() -> Bool {
        return speechSynthesizer.isSpeaking
    }
    
    public func stopSpeak() {
        speechSynthesizer.stopSpeaking(at: .immediate)
    }
    
    private func buildSpeechSynthesizer() {
        
        //简单配置一个AVAudioSession以便可以在后台播放声音，更多细节参考AVFoundation官方文档
        let session = AVAudioSession.sharedInstance()
        
//        if let error = try? session.setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.duckOthers) {
//            NSLog("AudioSession Error:\(error)")
//        }
        if let error = try? session.setCategory(AVAudioSession.Category.playback, options: .duckOthers) {
            NSLog("AudioSession Error:\(error)")
        }
        
        speechSynthesizer = AVSpeechSynthesizer()
        speechSynthesizer.delegate = self
    }
    
}

